package com.ruoyi.search.service;

import com.alibaba.fastjson.JSON;
import com.ruoyi.search.entity.SearchItem;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SearchService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Value("${menu.elasticsearch.index}")
    String index;

    public Map search(Integer page, Integer size, Map searchMap) throws IOException {
        String keyword = (String) searchMap.get("keyword");
        String minPrice = (String) searchMap.get("minPrice");
        String maxPrice =(String) searchMap.get("maxPrice");

        SearchRequest searchRequest = new SearchRequest(index);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        searchSourceBuilder.from((page-1)*size);
        searchSourceBuilder.size(size);



        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        if(!StringUtils.isEmpty(keyword)){
            MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders
                    .multiMatchQuery(keyword, "menu_name");
            boolQueryBuilder.must(multiMatchQueryBuilder);
        }


        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("menu_price");
        if(!StringUtils.isEmpty(minPrice)){
            rangeQueryBuilder.gte(minPrice);
        }
        if(!StringUtils.isEmpty(maxPrice)){
            rangeQueryBuilder.lte(maxPrice);
        }
        boolQueryBuilder.filter(rangeQueryBuilder);

        //高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("menu_name")
                .preTags("<strong style='color:red'>")
                .postTags("</strong>");
        searchSourceBuilder.highlighter(highlightBuilder);//highlighter

        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //解析结果
        SearchHits hits = searchResponse.getHits();//hits
        TotalHits totalHits = hits.getTotalHits();
        long total = totalHits.value;//hits-->total
        SearchHit[] hits_array = hits.getHits();
        //查询 命中
        List<SearchItem> searchItemList = Arrays.stream(hits_array).map(searchHit -> {
            String sourceAsString = searchHit.getSourceAsString();
            SearchItem searchItem = JSON.parseObject(sourceAsString, SearchItem.class);
            //解析 高亮
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            HighlightField highlightField = highlightFields.get("menu_name");
            if(highlightField!=null){
                Text[] fragments = highlightField.getFragments();
                if(fragments.length>0){
                    String menu_name = fragments[0].string();
                    searchItem.setMenu_name(menu_name);
                }
            }
            return searchItem;
        }).collect(Collectors.toList());

        Map map = new HashMap();
        map.put("total",total);//long
        map.put("searchItemList",searchItemList);//list

        return map;
    }
}
